package com.alexsh.service.bookspresentation.impl;

import com.alexsh.common.ApplicationContextHolder;
import com.alexsh.common.CommonFormatterUtils;
import com.alexsh.dao.impl.BooksRepository;
import com.alexsh.domain.Book;
import com.alexsh.service.bookspresentation.BookManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author Alexander Shmygin <AShmygin@luxoft.com>
 * @version 1.0
 */
@Service("bookInJsonManager")
public class BookInJsonManager implements BookManager {

    private BooksRepository bookRepository
        = (BooksRepository) ApplicationContextHolder.getBean("bookRepository");

    public String getContent() {
        HashMap<String, Book> books = bookRepository.getBooks();
        JSONArray jsonArray = new JSONArray();
        int totalItems = 0;
        for (Book book : books.values()) {
            jsonArray.put(populateJsonElement(book));
            totalItems++;
        }
        return getJson(jsonArray, totalItems);
    }

    public String getById(String bookId) {
        HashMap<String, Book> books = bookRepository.getBooks();
        Book book = books.get(bookId);
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(populateJsonElement(book));
        return getJson(jsonArray, 1);
    }

    private JSONObject populateJsonElement(Book book) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("id", book.getId());
            obj.put("title", book.getTitle());
            obj.put("authors", book.getAuthors());
            obj.put("pubDate", CommonFormatterUtils.dateToStr(book.getPubDate()));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    private String getJson(JSONArray jsonArray, int totalItems) {
        JSONObject responseObject = new JSONObject();
        try {
            responseObject.put("pageIndex", new Integer(1));
            responseObject.put("pageSize", new Integer(10));
            responseObject.put("totalPages", new Integer(1));
            responseObject.put("totalItems", totalItems);
            responseObject.put("books", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return responseObject.toString();
    }
}
